package spring.core.examples.validator.xml;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import spring.core.examples.xml.Person;

/**
 * Demonstrates validation using the Spring Validation interface.
 */
public class ApplicationSpring {

	/**
	 * Gets a bean from the spring application context
	 * 
	 * @param beanName
	 *            the bean name
	 * @return the bean
	 */
	private static Object getBean(String beanName) {
		return ValidatorContext.getInstance().getBean(beanName);
	}

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the arguments
	 */
	public static void main(String[] args) {
		// Retrieve a person from the spring context and modify it with an
		// error.
		Person myPerson = (Person) getBean("elke");
		myPerson.setAge(-5);

		// now validate that person using Spring Validator
		Validator myValidator = (Validator) getBean("personValidator");
		BeanPropertyBindingResult myResult = new BeanPropertyBindingResult(
				myPerson, myPerson.getClass().getSimpleName());
		myValidator.validate(myPerson, myResult);

		// print out the errors found in all translations
		MessageSource myMessageSource = (MessageSource) getBean("messageSource");
		for (ObjectError eachError : myResult.getAllErrors()) {
			for (Locale eachLocale : new Locale[] { Locale.GERMAN, Locale.US }) {
				System.out.println(myMessageSource.getMessage(
						eachError.getCodes()[0],
						new Object[] { myPerson.getFullName() }, eachLocale));
			}
		}
	}
}
